import React, { PureComponent } from 'react';
// 引入请求
import Axios from 'axios';
// 引入地址
import { webSite } from '../website';
// 引入样式
import './scss/novel.scss';
import { Carousel, message, Button, Modal } from 'antd';
// 引入仓库
import store from '../store/index';
export default class Novel extends PureComponent {
  constructor() {
    super()
    this.state = {
      // 搜索结果的列表
      novelAll: [],
      // 下标
      HomeIndex: 2,
      // 轮播图
      CarouselAll: [{ CarouselUrl: '', CarouselText: '' }, { CarouselUrl: '', CarouselText: '' }, { CarouselUrl: '', CarouselText: '' }, { CarouselUrl: '', CarouselText: '' }, { CarouselUrl: '', CarouselText: '' }],
      // 新书发布
      NewNovelAll: [],
      // 推荐书
      pushNovelAll: [],
      // 都市
      urbanlAll: [],
      // 我的书架数据
      bookshelfAll: [],
      // 删除的对话框
      visible: false,
      // 要删除的书的id
      novelId: 0
    }
    // state的写法
    this.unSubscribe = store.subscribe(() => {
      // 强制更新
      this.forceUpdate()
    })
  }
  componentWillUnmount () {
    this.unSubscribe()
    // 卸载异步操作设置状态
    this.setState = () => {
      return;
    }
  }
  componentDidMount () {
    Axios.create({
      baseURL: `${webSite}:3003`
    }).post("/getCarousel").then(err => {
      if (err.data.code === 'F0001') {
        let { Carousel, NewNovel } = err.data.CarouselAll
        this.setState({
          // 轮播图数据
          CarouselAll: Carousel,
          // 新书发布
          NewNovelAll: NewNovel
        })
      }
    }).catch(() => {
      message.error({ content: '网络错误', className: 'bulletChatMessage' });
    })
    this.getNewNovel()
  }
  // 请求新书
  getNewNovel = () => {
    Axios.create({
      baseURL: `${webSite}:3003`
    }).post("/getNewNovel").then(err => {
      if (err.data.code === 'U0001') {
        let { pushNovel } = err.data;
        // 把请求回来得到结果分成两个数组
        let pushNovelLeft = pushNovel.slice(0, 4);
        let pushNovelRight = pushNovel.slice(4);
        this.setState({
          pushNovelAll: pushNovelLeft,
          urbanlAll: pushNovelRight
        })
      }
    }).catch(() => {
      message.error({ content: '网络错误', className: 'bulletChatMessage' });
    })
  }
  // 切换下标
  setIndex = (int) => {
    const _this = this;
    if (int === 1) {
      let { userId } = store.getState().reducer;
      if (!userId) {
        // 用户没有登录跳转到首页
        this.props.history.replace('/')
        return;
      }
      // 用户登录了就获取用户的书架内容
      Axios.create({
        baseURL: `${webSite}:3003`
      }).post("/getBookshelfAll", { id: userId }).then(err => {
        if (err.data.code === 'N0003') {
          // 把从服务器获取的书架信息放到页面上
          _this.setState({
            bookshelfAll: err.data.data.reverse()
          })
        }
      }).catch(() => {
        message.error({ content: '网络错误,无法查看书架', className: 'bulletChatMessage' });
      })
    }
    this.setState({
      HomeIndex: int
    })
  }
  // 打开阅读器
  goReader = (list) => {
    // 把数据传给阅读器
    let Font = {
      novelText: list.novelText,
      novelUrl: list.novelUrl,
      id: list.id
    }
    let novelHref = list.novelHref;
    // 设置一个index
    let index = list.index;
    // 跳转到阅读器
    this.props.history.push({ pathname: "/novel/Reader", state: { Font, index, novelHref } });
  }
  // 删除电子书的对话框
  deleteNovel = (e, id) => {
    // 去掉冒泡事件
    e.stopPropagation();
    this.setState({
      visible: true,
      novelId: id
    });
  }
  // 关闭删除对话框
  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };
  // 删除某本电子书
  modalDeleteNovel = () => {
    let { novelId } = this.state;
    let { userId } = store.getState().reducer;
    if (!userId) {
      // 用户没有登录跳转到首页
      this.props.history.replace('/')
      return;
    }
    // 值一个为用户的id  一个为要删除的电子书得到id
    Axios.create({
      baseURL: `${webSite}:3003`
    }).post("/deleteNovelId", { id: userId, novelId }).then(err => {
      // 成功返回数据
      if (err.data.code === 'D0001') {
        message.success({ content: '删除成功', className: 'bulletChatMessage' })
        // 重新获取一次数据
        this.setIndex(1);
        // 关闭对话框
        this.handleCancel();
        return;
      }
    }).catch(() => {
      message.error({ content: '网络错误,无法删除', className: 'bulletChatMessage' });
    })
  }
  // 书架
  bookshelf = () => {
    let { bookshelfAll } = this.state;
    return (
      <div className='bookshelf'>
        <div className='bookshelf_title'>
          我的书架
        </div>
        {/* 删除的对话框 */}
        <Modal
          visible={this.state.visible}
          onCancel={this.handleCancel}
          footer={null}
          getContainer={() => document.getElementsByClassName('bookshelf')[0]}
          className='bookshelfDeleete'
          centered={true}
          bodyStyle={{
            width: '100%',
            height: '35vw',
            padding: '0'
          }}
        >
          <div className='bookshelfDeleete_body'>确认删除？</div>
          <div className='bookshelfDeleete_caozuo'>
            <div className='bookshelfDeleete_Cancel' onClick={this.handleCancel}>关闭</div>
            <div className='bookshelfDeleete_Ok' onClick={this.modalDeleteNovel}>删除</div>
          </div>
        </Modal>
        {/* 书架 */}
        <ul className='bookshelf_ul_box'>
          {
            bookshelfAll.length !== 0 ?
              bookshelfAll.map((list, index) => {
                return (
                  <li className='bookshelf_ul_box_li' key={list.id} onClick={() => this.goReader(list)}>
                    <div className='bookshelf_ul_box_li_left'>
                      <img src={list.novelImg} alt="电子书" />
                    </div>
                    <div className='bookshelf_ul_box_li_right'>
                      <h3>{list.novelText}</h3>
                      <div className='bookshelf_ul_box_li_right_action'>
                        {list.novelAuthor}
                      </div>
                      <div className='bookshelf_zhangjie'>
                        章节更新到第{list.novellang}章
                          <em>|</em>
                        您看到第{list.index + 1}章
                      </div>
                      <img src={require('./image/delete.png')} alt="删除" className='bookshelf_box_delete' onClick={(e) => this.deleteNovel(e, list.id)} />
                    </div>
                  </li>
                )
              }) : <li className='bookshelfBoxFalse'>您还没有收藏~</li>
          }
        </ul>
      </div>
    )
  }
  // 点击跳转到详情页
  goDetails = (url) => {
    Axios.create({
      baseURL: `${webSite}:3003`
    }).post("/goDetailsAll", { url }).then(err => {
      if (err.data.code === 'U0001') {
        // 跳转到文章详情页
        let novelAll = err.data.novelAll[0]
        this.props.history.push({ pathname: "/novel/details", state: novelAll });
      }
    }).catch(() => {
      message.error({ content: '网络错误', className: 'bulletChatMessage' });
    })
  }
  // 主页
  homeH = () => {
    let { CarouselAll, NewNovelAll, pushNovelAll, urbanlAll } = this.state;
    // 设置一个跟随页面变化的高度
    let CarouselHeight = document.getElementsByClassName('homeHCarousel')[0];
    let Cheight = CarouselHeight !== undefined ? CarouselHeight.offsetHeight : 140;
    const contentStyle = {
      height: `${Cheight}px`,
      color: '#fff',
      lineHeight: '100px',
      textAlign: 'center',
      background: '#fff',
    };
    return (
      <div className='homeH'>
        {/* 顶部轮播图 */}
        <div className='homeHCarousel'>
          <Carousel autoplay>
            <div>
              <h3 style={contentStyle}>
                <img src={CarouselAll[0].CarouselText} alt="1" onClick={() => this.goDetails(CarouselAll[0].CarouselUrl)} className='homeHCarouselBoxImg' />
              </h3>
            </div>
            <div>
              <h3 style={contentStyle}>
                <img src={CarouselAll[1].CarouselText} alt="2" className='homeHCarouselBoxImg' onClick={() => this.goDetails(CarouselAll[1].CarouselUrl)} />
              </h3>
            </div>
            <div>
              <h3 style={contentStyle}>
                <img src={CarouselAll[2].CarouselText} alt="3" className='homeHCarouselBoxImg' onClick={() => this.goDetails(CarouselAll[2].CarouselUrl)} />
              </h3>
            </div>
            <div>
              <h3 style={contentStyle}>
                <img src={CarouselAll[3].CarouselText} alt="4" className='homeHCarouselBoxImg' onClick={() => this.goDetails(CarouselAll[3].CarouselUrl)} />
              </h3>
            </div>
            <div>
              <h3 style={contentStyle}>
                <img src={CarouselAll[4].CarouselText} alt="5" className='homeHCarouselBoxImg' onClick={() => this.goDetails(CarouselAll[4].CarouselUrl)} />
              </h3>
            </div>
          </Carousel>
        </div>
        {/* 搜索框 */}
        <Button type='text' className='homeHInput' onClick={this.clickBtnSearch}>搜索您想看的小说</Button>
        {/* 热门小说 */}
        <div className='homeH_body_list'>
          <h3 className='homeH_body_list_h3'>热门小说<span>推荐</span></h3>
          <ul className='homeH_body_list_ul'>
            {
              pushNovelAll.length !== 0 ?
                pushNovelAll.map((list, index) => {
                  return (
                    <li key={index} onClick={() => this.goDetails(list.novelUrl)}>
                      <img src={list.novelImg} alt="封面" />
                      <h3 dangerouslySetInnerHTML={{ __html: list.novelName }}></h3>
                    </li>
                  )
                })
                : ''
            }
          </ul>
        </div>
        {/* 都市娱乐 */}
        <div className='homeH_body_list'>
          <h3 className='homeH_body_list_h3'>都市娱乐<span>推荐</span></h3>
          <ul className='homeH_body_list_ul'>
            {
              urbanlAll.length !== 0 ?
                urbanlAll.map((list, index) => {
                  return (
                    <li key={index} onClick={() => this.goDetails(list.novelUrl)}>
                      <img src={list.novelImg} alt="封面" />
                      <h3 dangerouslySetInnerHTML={{ __html: list.novelName }}></h3>
                    </li>
                  )
                })
                : ''
            }
          </ul>
        </div>
        {/* 展示 */}
        <div className='homeH_body'>
          <h3>品书试读<span>24小时热销新书</span></h3>
          <ul className='homeH_body_ul'>
            {
              NewNovelAll.length !== 0 ?
                NewNovelAll.map((list, index) => {
                  return (
                    <li key={index} onClick={() => this.goDetails(list.newUrl)}>
                      <div className='homeH_body_boxImg'>
                        <img src={list.novelImg} alt="封面" />
                      </div>
                      <div className='homeH_body_box'>
                        <h2 dangerouslySetInnerHTML={{ __html: list.novelName }}></h2>
                        <div className='homeH_body_box_const' dangerouslySetInnerHTML={{ __html: list.novelContent }}></div>
                        <div className='homeH_body_box_bottom'>
                          <div className='homeH_body_box_bottom_active' dangerouslySetInnerHTML={{ __html: list.novelAuthor }}></div>
                          <span className='homeH_body_box_bottom_style' dangerouslySetInnerHTML={{ __html: list.cate }}></span>
                        </div>
                      </div>
                    </li>
                  )
                })
                : ''
            }
          </ul>
        </div>
        {/* 底部内容 */}
        <div className='homeH_bottom'>
          <p>页面所有内容收集自互联网</p>
          <p>仅提供WEB页面服务，不承担责任</p>
          <p>如果侵犯了您的利益，将立即删除</p>
        </div>
      </div>
    )
  }
  // 跳转到搜索页面
  clickBtnSearch = () => {
    this.props.history.replace('/Novel/Search')
  }
  // 设置选中样式
  classSet = (int) => {
    let { HomeIndex } = this.state;
    if (int === HomeIndex) {
      return 'novel_buttom_left border';
    }
    return 'novel_buttom_left';
  }
  render () {
    let { HomeIndex } = this.state;
    return (
      <div className='novel'>
        {/* 主体 */}
        {/* onClick={this.clickBtnSearch} */}
        <div className='novel_body'>
          {
            HomeIndex === 1 ? this.bookshelf() : this.homeH()
          }
        </div>
        {/* 底部切换 */}
        <div className='novel_buttom'>
          <div className={this.classSet(1)} onClick={() => this.setIndex(1)}>
            <img src={require('./image/shujia.png')} alt="书架" width='22' />
          </div>
          <div className={this.classSet(2)} onClick={() => this.setIndex(2)}>
            <img src={require('./image/zhuye.png')} alt="主页" width='35' />
          </div>
        </div>
      </div>
    )
  }
}